PROJECTENGRAM

ABSTRACT CLASSES AND INTERFACES

Abstract Classes and Interfaces

Tags: #◇Computer Science #◇CCPROG3 #◇Abstract Classes and Interfaces #◇Code Snippets #◇M8


◇Key Definitions

An Abstract Class is a class that cannot be instantiated and is used as a base class for other classes to extend. It can have both abstract and non-abstract methods.
An Interface is a completely "abstract class" that is used to group related methods with empty bodies.

◇Theoretical Framework

In Java, abstraction is a fundamental principle of Object-Oriented Programming (OOP) that helps to reduce complexity and hide implementation details. Abstract Classes allow sharing code among closely related classes. They can hold state (fields) and have constructors. Interfaces represent a contract. They are used to guarantee that a class implements a specific set of methods, enabling multiple inheritance of type.

◇Code Implementation

『』
JAVA
// Abstract Class Example
abstract class Animal {
    protected String name;
    
    public Animal(String name) {
        this.name = name;
    }
    
    // Abstract method (does not have a body)
    public abstract void makeSound();
    
    // Regular method
    public void sleep() {
        System.out.println("Zzz");
    }
}

// Interface Example
interface Movable {
    void move();
}

// Concrete Class implementing both
class Dog extends Animal implements Movable {
    public Dog(String name) {
        super(name);
    }
    
    @Override
    public void makeSound() {
        System.out.println("Woof");
    }
    
    @Override
    public void move() {
        System.out.println("Running");
    }
}

◇Syntax Breakdown

abstract keyword: Used before class to define an abstract class, and before method signatures to define abstract methods. interface keyword: Used to define an interface. extends: Keyword used by a class to inherit from an abstract class. implements: Keyword used by a class to implement an interface.

◇Complexity Analysis

Abstract classes and interfaces do not inherently change runtime complexity, but they affect architectural complexity. Interfaces increase architectural flexibility (loose coupling) but might require more classes to define behaviors. Method resolution at runtime (polymorphism) incurs a very slight overhead (virtual method tables).

◇References & Navigation

CONFIRMATION // 理解度の確認

ACTIVE RECALL VERIFICATION

Select an answer to verify conceptual comprehension and reveal the technical rationale.

Q1

What is a key characteristic of an Abstract Class?

Q2

How does an Interface differ from an Abstract Class in terms of inheritance?

Q3

Which keyword is used by a class to guarantee it fulfills the contract of an Interface?

Q4

In the provided code, why does the Animal class have a constructor if it cannot be instantiated?

Q5

How do abstract classes and interfaces affect the complexity of a program?

Abstract Classes and Interfaces | PROJECT ENGRAM